const cheerio = require('cheerio')
const { request ,request2} = require('./request')
const tag = '关注' // 关注的人

let requestInterval = 350

// 删除多个
async function deleteMultiple(config) {

  let { start, end, interval,cookie } = config
  requestInterval = interval || 350
  if(!start || !end){
    if(start){
      end = start
    }else if(end){
      start = end
    }else{
      console.log(`${tag}: 请设置开始和结束页 `)
      return false
    }
  }else if(start > end){
    start = end
  }

  const list = await getMultiplePage(start,end)
  const len = list.length
  if (len === 0) {
    console.log(`${tag}: 完成`)
    return false
  }

  for (let index = 0; index <list.length; index++) {
    console.log(`正在取消关注:${list[index].un}`)
   const status = await deleteOne(list[index])
    if(status === true){
      console.log(`${tag}: >>> 接口限制 <<< , 请明天再尝试`)
      return false
    }
  }
  console.log(`${tag}: 执行完毕`)
}

// 取消关注
async function deleteOne(params) {
  const fd = new URLSearchParams()
  Object.keys(params).forEach(key => {
    fd.append(key, params[key])
  })

  const url = 'https://tieba.baidu.com/home/post/unfollow'
  const response = await request(url, {
    method: 'POST',
    body: fd
  })
  const data = await response.json()

  return new Promise(resolve => {
    setTimeout(() => {
      if (data.no === 0) {
        console.log(`${tag}: 操作结果`,data)
        resolve(false)
      } else {
        console.log(`${tag}: 清理错误:`, JSON.stringify(data))
        resolve(true)
      }
    }, requestInterval)
  })
}

// 获取多页
async function getMultiplePage(start, end) {
  console.log(`${tag}: 获取, 页面:${start}->${end}`)
  const data = []
  for (let page = start; page <= end; page++) {
    let list = await getOnePage(page)
    data.push(...list)
  }
  console.log(`${tag}: 获得总数: ${data.length}`)
  return data
}

// 获取一页
async function getOnePage(page) {
  const url = `https://tieba.baidu.com/i/i/concern?pn=${page}`
  const response = await request(url)
  const data = await response.text()
  const $ = cheerio.load(data)
    const list = $('input.btn_unfollow').map((index, el) => {
    return {
      cmd: 'unfollow',
      tbs: $(el).attr('tbs'),
      un: $(el).attr('name'),
      id: $(el).attr('portrait')
    };
});
  
  return new Promise(resolve=>{
    setTimeout(()=>{
      console.log(`${tag}: 获得, 页面:${page}, 数量:${list.length}`)
      resolve(list)
    },requestInterval)
  })
}

module.exports.deleteConcerns = deleteMultiple